package com.ma.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.ma.pojo.Role;
import com.ma.pojo.User;
import com.ma.service.role.RoleServiceImpl;
import com.ma.service.user.UserService;
import com.ma.service.user.UserServiceImpl;
import com.ma.utils.Constants;

import com.ma.utils.PageSupport;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.StringUtils;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals( "savepwd") && method != null) {
            this.updatePwd(req, resp);
        }else if (method.equals( "pwdmodify") && method != null) {
            this.pwdmodify(req, resp);
        }else if (method.equals("query") && method != null){
            this.query(req,resp);
        }
        // 想添加新的增删改查，直接用if(method != "savepwd" && method != null);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag = false;

        if (attribute!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) attribute).getId(),newpassword);
            if (flag){
                req.setAttribute("messgae","密码修改成功，请退出，请使用新密码登录");
                //密码修改成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("messgae","密码修改失败");
            }

        }else {
            req.setAttribute("messgae","新密码有问题");
        }
        try {
            req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        //万能的Map
        HashMap<String, String> resultMap = new HashMap<>();
        if (attribute == null){
            //当前session过期
            resultMap.put("result","sessionerror");

        }else if(StringUtils.isNullOrEmpty(oldpassword)){
            resultMap.put("result","error");
        }else {
            String userPassword = ((User) attribute).getUserPassword();//session中用户的密码
            if (oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //重点，难点
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;
        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;
        //第一次走这个请求，一定是第一页，且页面大小是固定的
        int pagaSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;


        if (queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);//给查询赋值0，1，2，3
        }
        if (pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户总数（分页：上一页 下一页）
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.getCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pagaSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = ((int)(totalCount/pagaSize))+1;

        //控制首页和尾页
        if (currentPageNo<1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pagaSize);

        req.setAttribute("userList",userList);
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);
        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
